package com.adee.gulimall.search.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

@Data
@Configuration
@ConfigurationProperties(prefix = "my.elasticsearch")
public class ElasticSearchConfig {
    /**
     * spring:
     *   elasticsearch:
     *     uri-list:
     *       - 101.42.43.39:9200
     *       - 101.42.43.39:9201
     *       - 101.42.43.39:9202
     */
    // 注意：list不可使用@Value注解，要使用类上的@ConfigurationProperties(prefix = "my.elasticsearch")
    private List<String> uriList;
    @Value("${hello.name}")
    private String hello;
    @Value("${my.elasticsearch.name}")
    private String name;
    @Value("${spring.elasticsearch.uris}")
    private String uris;
    @Bean
    public ElasticsearchClient esRestClient() {
        System.out.println(name);
        List<HttpHost> uris = uriList.stream().map(u -> {
            String[] uri = u.split(":");
            return new HttpHost(uri[0], Integer.parseInt(uri[1]));
        }).collect(Collectors.toList());
        // 创建低级客户端
        RestClient restClient = RestClient
                .builder(uris.toArray(new HttpHost[uris.size()]))
                .build();


        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);

        return client;
        // 创建索引
        //CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
        // 响应状态
        //Boolean acknowledged = createIndexResponse.acknowledged();
        //System.out.println("索引操作 = " + acknowledged);

        // 关闭ES客户端
        //transport.close();
        //restClient.close();
    }
}
